from dao import Dao
from model.post import Post
from model.user import User
from model.subject import Subject
from bson.dbref import DBRef

class PostDao(Dao):
    def __init__(self):
        Dao.__init__(self, Post)
        self.collection = 'posts'

    def save(self, model):
        """Updates an existing document or inserts a new document, depending on its document parameter.
        Arguments:
            model --- The Model object with id,  if model is a dict type, the dbref field must be DBRef type
        Return:
            The '_id' value of to_save or [None] if manipulate is False and to_save has no _id field.
        """
        # The ID field must exist
        if isinstance(model, dict):
            return self.db.save(self.collection, model)
        else:
            _dict = model.__dict__
            if isinstance(model.subject, Subject):
                _dict['subject'] = DBRef('subjects', model.subject._id)
            else:
                _dict['subject'] = None # For root
                
            if isinstance(model.author, User):
                _dict['author'] = DBRef('users', model.author._id)
            else:
                _dict['author'] = None # For root
                                
            return self.db.save(self.collection, _dict)